package com.itcoon.cloud.framework.security.service;

import com.itcoon.cloud.framework.ex.Assertion;
import com.itcoon.cloud.framework.security.ex.SecurityResponseEnum;
import com.itcoon.cloud.framework.security.model.UserPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

public abstract class AbstractUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    private final List<IUserPrincipalAdvice> principalAdvices;

    public AbstractUserDetailsService(List<IUserPrincipalAdvice> principalAdvices) {
        this.principalAdvices = principalAdvices;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserPrincipal user = queryUser(username);
        Assertion.assertNotNull(user).raise(SecurityResponseEnum.USER_MISSING);
        for (IUserPrincipalAdvice principalAdvice : principalAdvices) {
            principalAdvice.handle(user);
        }
        return user;
    }

    public abstract UserPrincipal queryUser(String username);
}
